const gulp = require('gulp');

const connect = require('gulp-connect');// gulp服务器

const less = require('gulp-less');// less编译
const cssmini = require('gulp-clean-css');// css压缩
const cssautoprefix = require('gulp-autoprefixer');// css添加前缀

const htmlmini = require('gulp-htmlmin');// html压缩

const jsmini = require('gulp-uglify');// js压缩

const babel = require('gulp-babel');// es6转码

// const imagemin = require('gulp-imagemin');// 以下都是图片压缩模块
// const imageminPngquant = require('imagemin-pngquant');
// const imageminOptipng = require('imagemin-optipng');
// const imageminGifsicle = require('imagemin-gifsicle');
// const imageminJpegtran = require('imagemin-jpegtran');
const tinify = require("tinify");// 高效的压缩
const fs = require('fs');

const cached = require('gulp-cached');// 增量编译
const remember = require('gulp-remember');

const concat = require('gulp-concat');// 合并

const htmlMiniOptions = {
  removeComments: true,// 清除HTML注释
  collapseWhitespace: true,// 压缩HTML
  collapseBooleanAttributes: false,// 省略布尔属性的值 <input checked="true"/> ==> <input />
  removeEmptyAttributes: false,// 删除所有空格作属性值 <input id="" /> ==> <input />
  removeScriptTypeAttributes: true,// 删除<script>的type="text/javascript"
  removeStyleLinkTypeAttributes: true,// 删除<style>和<link>的type="text/css"
  minifyJS: true,// 压缩页面JS
  minifyCSS: true// 压缩页面CSS
}

const workplace = 'workplace/';// 工作目录
const dist = 'dist/';// 构建完成目录

const isAddimgs = process.argv.includes('--addimgs');// 有新增压缩的图
const isFirstGulp = process.argv.includes('--firstgulp');// 第一次gulp

const tasks = ['css-build', 'es6toes5', 'watch'];// base
if(isAddimgs) tasks.push('imagemini');
if(isFirstGulp) tasks.concat(['copystatic', 'imagemini']);


/** 启动一个server */
gulp.task('start-server', () => {

  connect.server({
    port: 9090,
    root: dist,
    livereload: true,
  });
});


/** index.html热更新 */
gulp.task('server-reload', () => {

  gulp.src(workplace + 'index.html')
  .pipe(htmlmini(htmlMiniOptions))
  .pipe(gulp.dest(dist))
  .pipe(connect.reload());
});


/** css预处理语言编译 */
gulp.task('css-build', ['server-reload'], () => {

  gulp.src(workplace + 'css/*.less')
  .pipe(cached('css-build-cached'))
  .pipe(less())
  .pipe(cssmini({ compatibility: 'ie8' }))
  .pipe(cssautoprefix())// browsers官方推荐设置到package.json，以便其他插件共享
  .pipe(remember('css-build-cached'))
  .pipe(concat('app.css'))
  .pipe(gulp.dest(dist + 'css'));
});


/** es6处理 */
gulp.task('es6toes5', () => {

  gulp.src(workplace + 'js/*.js')
  .pipe(cached('es6toes5-cached'))
  .pipe(babel())
  .pipe(jsmini())
  .pipe(remember('es6toes5-cached'))
  .pipe(concat('app.js'))
  .pipe(gulp.dest(dist + 'js'));
});


/** 图片压缩 */
gulp.task('imagemini', () => {

  // gulp.src(workplace + 'images/*.{png,jpg,gif}')
  // .pipe(cached('imagemini-cached'))
  // .pipe(imagemin({
  //   progressive: true,
  //   use: [
  //     imageminGifsicle({ interlaced: true }),
  //     imageminPngquant(),
  //     imageminJpegtran({  }),
  //     imageminOptipng({ optimizationLevel: 3 })
  //   ]
  // })).pipe(gulp.dest(dist + 'images'));

  // tinypng
  let imgsLen = 0;
  let minied = 0;
  const tinifyCount = {
    used: 0,
    total: 500,
  }
  tinify.key = tinypngkey;
  tinify.validate(err => {
    if (err) throw err;
    tinifyCount.used = tinify.compressionCount;
  });

  let readdir = '';
  if(isAddimgs) readdir = workplace + 'add-images';
  else readdir = workplace + 'images';

  fs.readdir(readdir, (err, files) => {
    if(err) throw err;

    imgsLen = files.length;
    console.log('本次压缩：' + imgsLen, '剩余：' + tinifyCount.used + '/' + 500);

    files.forEach(file => {

      fs.readFile(readdir + '/' + file, (err, sourceData) => {
        if(err) throw err;

        tinify.fromBuffer(sourceData).toBuffer((err, resultData) => {
          if(err) throw err;

          fs.writeFile(dist + 'images/' + file, resultData, err => {
            if(err) throw err;

            console.log('成功压缩并写入：' + ++minied + '/' + imgsLen);
          });
        });
      });
    });
  });
});


/** 复制static */
gulp.task('copystatic', () => {

  gulp.src(workplace + 'static/*/*.*')
  .pipe(gulp.dest(dist + 'static'));
});


/** 监听文件变化作出合适任务 */
gulp.task('watch', () => {

  gulp.watch(workplace + 'index.html', ['server-reload']);
  gulp.watch(workplace + 'css/*.less', ['css-build']);
  gulp.watch(workplace + 'js/*.js', ['es6toes5']);
});

gulp.task('default', ['start-server', 'css-build', 'es6toes5', 'copystatic', 'imagemini', 'watch']);